const { SerialPort } = require('serialport');

class COM {
  constructor() {
    this.port = null;
  }
  async COM_CONNECT_ACTION(paylod) {
    this.COM_CLOSE_ACTION().then(() => {
      return new Promise((resolve, reject) => {
        let port = new SerialPort(paylod.config, (err) => {
          console.log(err);
          if (err) {
            port = null;
            this.port = null;
          } else {
            this.port = port;
          }
          resolve();
        });

        // 当串口打开时触发
        port.on('open', (res) => {
          paylod.mainWindow.webContents.send('Com-open', res);
        });
        // 监听串口数据
        port.on('data', (res) => {
          console.log(res);
          paylod.mainWindow.webContents.send('Com-data', res);
        });
        port.on('error', (err) => {
          console.error('Error:', err.message);
          paylod.mainWindow.webContents.send('Com-error', err);
        });
      });
    });
  }
  COM_CLOSE_ACTION(paylod) {
    return new Promise((resolve, reject) => {
      if (this.port) {
        this.port.close((err) => {
          if (err) {
            console.error('Failed to close serial port:', err);
          } else {
            console.log('Serial port is closed');
          }
          this.port = null;
          resolve();
        });
      } else {
        this.port = null;
        resolve();
      }
    });
  }
}

export default COM;
